package com.harboursoftware.xstorage.db.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.harboursoftware.xstorage.util.Configuration;

/**
 * 
 * @author Simon Leung
 * @since 0.1
 */
public class DatabaseProviderImpl implements DatabaseProvider {
    private final static Logger log = LoggerFactory.getLogger(DatabaseProviderImpl.class);
    private final static String CONFIG_KEY_JDBC_DRIVER = "jdbc.driver";
    private final static String CONFIG_KEY_JDBC_URL = "jdbc.url";
    private final static String CONFIG_KEY_JDBC_USERNAME = "jdbc.username";
    private final static String CONFIG_KEY_JDBC_PASSWORD = "jdbc.password";

    private static String jdbcDriver;
    private static String jdbcUrl;
    private static String jdbcUsername;
    private static String jdbcPassword;

    private static DatabaseProviderImpl instance = new DatabaseProviderImpl();

    static {
        Configuration config = Configuration.getInstance();
        jdbcDriver = config.getString(CONFIG_KEY_JDBC_DRIVER);
        jdbcUrl = config.getString(CONFIG_KEY_JDBC_URL);
        jdbcUsername = config.getString(CONFIG_KEY_JDBC_USERNAME);
        jdbcPassword = config.getString(CONFIG_KEY_JDBC_PASSWORD);
        
        log.info("database driver : " + jdbcDriver);
        log.info("database url : " + jdbcUrl);
        log.info("database username : " + jdbcUsername);
        log.info("database password : " + jdbcPassword);
        DbUtils.loadDriver(jdbcDriver);
    }

    // 单例模式，不能实例化。
    protected DatabaseProviderImpl() {
    }

    public Connection getConnection() throws SQLException {
        // TODO ：连接池
        return DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);

    }

    public static DatabaseProviderImpl getInstance() {
        return instance;
    }
}
